package com.ledim.adapter.base;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import com.ledim.itf.LedimOnItemClickListener;
import com.letv.core.utils.BaseTypeUtils;
import java.util.ArrayList;
import java.util.List;

/**
 * pagerAdapter基类
 *
 * @author zhuqiao
 */
public abstract class LetvBasePagerAdapter<T> extends PagerAdapter {

    protected Context mContext;
    protected List<T> mList = new ArrayList<T>();

    /**
     * item点击事件回调
     */
    private LedimOnItemClickListener mOnItemClickListener;

    public LetvBasePagerAdapter(Context context, List<T> list) {
        mContext = context;
        mList = list;
    }

    public void setOnItemClickListener(LedimOnItemClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    @Override
    public int getCount() {
        return BaseTypeUtils.isListEmpty(mList) ? 0 : mList.size();
    }

    public T getItem(int position) {
        if (!BaseTypeUtils.isListEmpty(mList) && mList.size() > position) {
            return mList.get(position);
        }
        return null;
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        final View view = fetchView(mList.get(position));
        if (mOnItemClickListener != null) {
            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    mOnItemClickListener.onItemClick(position, getItem(position), view);
                }
            });
        }
        container.addView(view);
        return view;
    }

    /**
     * setPrimaryItem
     *
     * @param container
     * @param loopPosition
     *         循环中的位置
     * @param realPosition
     *         正确的位置
     * @param object
     */
    public void setPrimaryItem(ViewGroup container, int loopPosition, int realPosition,
                               Object object) {
        setPrimaryItem(container, realPosition, object);
    }

    /**
     * 获取itemView.由子类重写
     *
     * @param t
     * @return
     */
    protected abstract View fetchView(T t);
}
